package com.block.product.service.union;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import com.block.product.service.utils.YueDaiBaoUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class YueDaiBaoUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();
    @Autowired
    private MemberSourceInfoMapper memberSourceInfoMapper;

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getCheckUrl();
        String mobileMd5 = SecureUtil.md5(uniLoginDTO.getMobile()).toLowerCase();

        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectByMobileMd5(mobileMd5);
        Map<String, Object> map = new HashMap<>();
        map.put("age", memberSourceInfo.getAge());
        map.put("channelCode", apiInfoParam.getApiCode());
        map.put("gender", memberSourceInfo.getSex());
        map.put("city", memberSourceInfo.getCity());
        map.put("cityCode", memberSourceInfo.getCityCode());
        map.put("profession", YueDaiBaoUtils.getJob(memberSourceInfo.getGongzuo()));
        map.put("loanAmount", YueDaiBaoUtils.getLoanAmount(memberSourceInfo.getLoanAmount()));
        map.put("zhima", YueDaiBaoUtils.getZhiMa(memberSourceInfo.getZhima()));
        map.put("socialSecurity", YueDaiBaoUtils.getSheBao(memberSourceInfo.getShebao()));
        map.put("providentFund", YueDaiBaoUtils.getGjj(memberSourceInfo.getGjj()));
        map.put("vehicle", YueDaiBaoUtils.getCar(memberSourceInfo.getCar()));
        map.put("house", YueDaiBaoUtils.getHouse(memberSourceInfo.getHouse()));

        String data =encrypt(JSON.toJSONString(map),apiInfoParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("businessCode", apiInfoParam.getApiCode());
        paramMap.put("data",data);

        log.info("【贷悦宝】撞库开始【queryUrl】{}【map】{}【paramMap】{}", checkUrl,JSON.toJSONString(map), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【贷悦宝】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        loginResult.setCode(String.valueOf(code));
        loginResult.setMessage(msg);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(map));
        JSONObject jsonObject = resultObject.getJSONObject("data");
        Integer status = jsonObject.getInteger("status");
        if (StrUtil.equals(String.valueOf(code), "200") && StrUtil.equals(String.valueOf(status), "0")) {
            loginResult.setSuccess(true);
        }
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String mobileMd5 = SecureUtil.md5(uniLoginDTO.getMobile()).toLowerCase();
        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectByMobileMd5(mobileMd5);
        Map<String, Object> map = new HashMap<>();
        map.put("age", memberSourceInfo.getAge());
        map.put("name", memberSourceInfo.getRealname());
        map.put("phone", memberSourceInfo.getMobile());
        map.put("idCard", memberSourceInfo.getIdcard());
        map.put("ip", memberSourceInfo.getReqIp());
        map.put("channelCode", apiInfoParam.getApiCode());
        map.put("gender", memberSourceInfo.getSex());
        map.put("city", memberSourceInfo.getCity());
        map.put("cityCode", memberSourceInfo.getCityCode());
        map.put("profession", YueDaiBaoUtils.getJob(memberSourceInfo.getGongzuo()));
        map.put("loanAmount", YueDaiBaoUtils.getLoanAmount(memberSourceInfo.getLoanAmount()));
        map.put("zhima", YueDaiBaoUtils.getZhiMa(memberSourceInfo.getZhima()));
        map.put("socialSecurity", YueDaiBaoUtils.getSheBao(memberSourceInfo.getShebao()));
        map.put("providentFund", YueDaiBaoUtils.getGjj(memberSourceInfo.getGjj()));
        map.put("vehicle", YueDaiBaoUtils.getCar(memberSourceInfo.getCar()));
        map.put("house", YueDaiBaoUtils.getHouse(memberSourceInfo.getHouse()));

        String data =encrypt(JSON.toJSONString(map),apiInfoParam.getApiSecret());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("businessCode", apiInfoParam.getApiCode());
        paramMap.put("data",data);

        log.info("【贷悦宝】联登开始【queryUrl】{}【map】{}【paramMap】{}", checkUrl,JSON.toJSONString(map), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【贷悦宝】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        loginResult.setCode(String.valueOf(code));
        loginResult.setMessage(msg);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(map));
        JSONObject jsonObject = resultObject.getJSONObject("data");
        String status = jsonObject.getString("status");

        if (StrUtil.equals(String.valueOf(code), "200") && StrUtil.equals(status, "1")) {
            String downUrl = jsonObject.getString("downUrl");
            loginResult.setSuccess(true);
            loginResult.setLoginUrl(downUrl);
        }
        return loginResult;
    }


    public static String encrypt(String str, String key) {
        try {
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encrypted =
                    cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            log.error("AES 加密异常", e);
            throw new RuntimeException(e);
        }
    }

}
